package com.lyh.hkcloud.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;

/**
 * @author Administrator
 */
public abstract class BaseJsonViewAdapter<K> extends BaseAdapter {
    private JSONArray list;
    private Context context;

    public BaseJsonViewAdapter(Context context, JSONArray list) {
        this.list = list;
        this.context = context;
    }

    @Override
    public final int getCount() {
        return list.length();
    }

    @Override
    public final JSONObject getItem(int position) {
        return list.optJSONObject(position);
    }

    @Override
    public final long getItemId(int position) {
        return position;
    }

    @Override
    public final View getView(int position, View convertView, ViewGroup parent) {
        K holder;
        JSONObject obj = list.optJSONObject(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    getItemResuId(), null);
            holder = getTag();
            initItem(position, holder, convertView, obj);
            convertView.setTag(holder);
        } else {
            holder = (K) convertView.getTag();
        }
        setItem(position, holder, obj);
        return convertView;
    }

    K getTag() {
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        Class<K> type = (Class<K>) superClass.getActualTypeArguments()[0];
        try {
            return type.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    abstract protected int getItemResuId();

    abstract protected void initItem(int position, K holder, View v, JSONObject obj);

    abstract protected void setItem(int position, K holder, JSONObject obj);

}

